#!/usr/bin/env python
#
# Copyright 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import webapp2
import cgi
import os
import urllib
import jinja2

from google.appengine.api import users
from google.appengine.ext import ndb


JINJA_ENVIRONMENT = jinja2.Environment(
    loader=jinja2.FileSystemLoader(os.path.dirname(__file__)),
    extensions=['jinja2.ext.autoescape'])

project_name = 'default'

class Task(ndb.Model):
	owner       = ndb.UserProperty()
	description = ndb.StringProperty(indexed=False)
	date        = ndb.DateTimeProperty(auto_now_add=True)
	blocking	= ndb.KeyProperty(kind='Task')
	url_key		= ndb.ComputedProperty(lambda self: self.key.urlsafe())


class MainHandler(webapp2.RequestHandler):
	def get(self):
		project_key = ndb.Key('Project', project_name)

		task_query = Task.query(ancestor=project_key)
		tasks = task_query.fetch(10)

		if users.get_current_user():
			url = users.create_logout_url(self.request.uri)
			url_linktext = 'Logout'
		else:
			url = users.create_login_url(self.request.uri)
			url_linktext = 'Login'
		# Write the submission form and the footer of the page
		template_data = { 	'url' : url,
							'url_link_text': url_linktext ,
							'tasks' : tasks}

		template = JINJA_ENVIRONMENT.get_template('index.html')
		self.response.write(template.render(template_data))

class AddHandler(webapp2.RequestHandler):
	def post(self):

		if self.request.get('parent') == 0:
			parentKey = ndb.Key('Project', project_name)
		else:
			parentKey = ndb.Key('Task', 123) #self.request.get('parent')
		
		task = Task()

		user = users.get_current_user()
		if user:
			task.owner = user

		task.description = self.request.get('task_description')
		blocking_key = ndb.Key(urlsafe=self.request.get('url_key'))
		task.blocking = blocking_key

		task.put()

		self.redirect('/')
		self.response.write("You just added a new task: ")

app = webapp2.WSGIApplication([
	('/', MainHandler),
	('/add', AddHandler)
], debug=True)
